import * as React from 'react';
import { Dialog, DialogType, DialogFooter } from 'office-ui-fabric-react/lib/Dialog';
import { PrimaryButton, DefaultButton } from 'office-ui-fabric-react/lib/Button';
// https://docs.microsoft.com/zh-cn/javascript/api/word/Word.ContentControl?view=office-js#properties

export default class ControlExample extends React.Component<
  {},
  {
    hideDialog: boolean;
  }
  > {
  constructor(props: {}) {
    super(props);
    this.state = {
      hideDialog: true
    };
  }

  componentDidMount() {
    // Office.context.document.addHandlerAsync(
    //   Office.EventType.DocumentSelectionChanged, this.getControl, function (result) {

    //   }
    // );

  }

  // 获取点击选择对象的内容
  getControl = () => {
    Word.run(function (context) {

      // Queue a command to get the current selection and then
      // create a proxy range object with the results.
      var range = context.document.getSelection();
      range.load()

      return context.sync().then(function () {
        const parentContentControl = range.parentContentControl
        const contentControls = range.contentControls
        console.info('contentControls', contentControls)

        // if (contentControl) {
        //   console.info('contentControl', contentControl.text, contentControl.title, contentControl)
        // }
      });

    }).catch(function (error) {
      console.log('Error: ', error);
      // if (error instanceof OfficeExtension.Error) {
      //   console.log('Debug info: ' + JSON.stringify(error.debugInfo));
      // }
    });
  }

  handleClick = (context) => {
    // 在word里点击的时候 判断内容是不是有指定标签的?
    console.info('点击')


    // TODO 给指定的内容 绑事件

    function addSelectionHandler() {
      Office.context.document.bindings.getByIdAsync("myTable", function (result) {
        result.value.addHandlerAsync("bindingSelectionChanged", myHandler);
      });
    }

    function myHandler() {
      console.info('获取绑定的id') // 和content control的 文字
    }

    // Display the user's current selection.
    function showSelection() {
      Office.context.document.getSelectedDataAsync(
        Office.CoercionType.Text,                        // coercionType
        {
          valueFormat: "formatted",   // valueFormat
          filterType: Office.FilterType.All //  |'all'| visible
        },            // filterType
        function (result) {            // callback
          var dataValue;
          dataValue = result.value;
          console.info('Selected data is: ' + dataValue);
        });
    }
    // Get the text from the selected cells in the document, and display it in the add-in.
    function getSelectedText() {
      Office.context.document.getSelectedDataAsync(
        Office.CoercionType.Text,
        { asyncContext: 'Some related info' },
        function (result) {
          if (result.status === Office.AsyncResultStatus.Failed) {
            console.error(result.error);
          }
          else {

            console.info(result.value, result.asyncContext);
          }
        }
      );
    }



  }




  public render() {

    return (
      <div>
        <PrimaryButton secondaryText="Opens the insert paragraphs Sample Dialog" onClick={this._showDialog} text="插入段落" />
        <Dialog
          hidden={this.state.hideDialog}
          onDismiss={this._closeDialog}
          dialogContentProps={{
            type: DialogType.largeHeader,
            title: '测试绑定',
            subText:
              'Your Inbox has changed. No longer does it include favorites, it is a singular destination for your emails.'
          }}
          modalProps={{
            isBlocking: true,
            containerClassName: 'ms-dialogMainOverride'
          }}
        >
          <div className="ms-form-group">
            <PrimaryButton onClick={this.createContentControl} text="createContentControl" />
            <PrimaryButton onClick={this.getContentControlByTag} text="getContentControlByTag" />
          </div>
          <br />
          <div className="ms-form-group">
            <PrimaryButton onClick={this.bindContentControl} text="bindContentControl" />
            <PrimaryButton onClick={this.displayBindingType} text="displayBindingType" />
            <PrimaryButton onClick={this.addBindingFromPrompt} text="addBindingFromPrompt 方法不存在" />
          </div>

          <DialogFooter>
            <PrimaryButton onClick={this._closeDialog} text="Save" />
            <DefaultButton onClick={this._closeDialog} text="Cancel" />
          </DialogFooter>
        </Dialog>
      </div>
    );
  }

  private _showDialog = (): void => {
    this.setState({ hideDialog: false });
  };

  private _closeDialog = (): void => {
    this.setState({ hideDialog: true });
  };

  createContentControl = () => {
    Word.run(function (context) {
      const serviceNameRange = context.document.getSelection();

      var myContentControl = serviceNameRange.insertContentControl();
      myContentControl.tag = "chart";
      myContentControl.title = "title1";
      myContentControl.placeholderText = "请随便点输入1";
      myContentControl.appearance = "Hidden"; // Word.ContentControlAppearance "BoundingBox" | "Tags" | "Hidden";
      myContentControl.style = "Quote";
      myContentControl.color = "white";
      // myContentControl.insertText("这是一个contentControl", 'replace');
      myContentControl.cannotEdit = true;

      return context.sync();
    }).catch(function (error) {
      console.log("Error: " + error);
    });
  }

  getContentControlByTag = () => {
    // Run a batch operation against the Word object model.
    Word.run(function (context) {

      // Create a proxy object for the content controls collection that contains a specific tag.
      var contentControlsWithTag = context.document.contentControls.getByTag('chart');

      // Queue a command to load the tag property for all of content controls.
      context.load(contentControlsWithTag, 'tag');

      // Synchronize the document state by executing the queued commands,
      // and return a promise to indicate task completion.
      return context.sync().then(function () {
        if (contentControlsWithTag.items.length === 0) {
          console.log('No content control found.');
        }
        else {
          // Queue a command to get the HTML contents of the first content control.
          var html = contentControlsWithTag.items[0].getHtml();

          // Synchronize the document state by executing the queued commands,
          // and return a promise to indicate task completion.
          return context.sync()
            .then(function () {
              console.log('Content control HTML: ' + html.value);
            });
        }
      });
    })
      .catch(function (error) {
        console.log('Error: ' + JSON.stringify(error));
        if (error instanceof OfficeExtension.Error) {
          console.log('Debug info: ' + JSON.stringify(error.debugInfo));
        }
      });
  }


  bindByTitle = () => {
    // 显示
    Office.context.document.bindings.addFromNamedItemAsync('title2',
      Office.BindingType.Text, { id: 'test1' },
      function (result) {
        Office.select("bindings#test1").setDataAsync('文字 标题', { coercionType: 'text' });
      }
    );
  }


  // The following example creates a text binding in Word to a rich text content control named "FirstName",
  // assigns the id "firstName", and then displays that information.
  bindContentControl = () => {
    Office.context.document.bindings.addFromNamedItemAsync('title1',
      Office.BindingType.Text, { id: 'firstName' },
      function (result) {
        if (result.status === Office.AsyncResultStatus.Succeeded) {
          console.info('Control bound. Binding.id: '
            + result.value.id + ' Binding.type: ' + result.value.type);
        } else {
          console.info('Error:', result.error.message);
        }
      }
    );

    // 显示
    Office.select("bindings#firstName").setDataAsync('替换后的文字', { coercionType: 'text' });
  }

  addBindingFromPrompt = () => {
    Office.context.document.bindings.addFromPromptAsync(
      Office.BindingType.Text,
      { id: 'MyBinding', promptText: 'Select text to bind to.' },
      function (asyncResult) {
        console.info('Added new binding with type: ' + asyncResult.value.type + ' and id: ' + asyncResult.value.id);
      });
  }

  displayBindingType = () => {
    Office.context.document.bindings.getByIdAsync('firstName', function (asyncResult) {
      console.info('Retrieved binding with type: ' + asyncResult.value.type + ' and id: ' + asyncResult.value.id);
    });
  }





  // 事件监听
  handleViewSelectionChange = () => {
    Office.context.document.addHandlerAsync(
      Office.EventType.ViewSelectionChanged,
      getActiveView
    );
    getActiveView();

    // Get the active view's name and type.
    function getActiveView() {
      Office.context.document.getSelectedViewAsync(  // 不存在 直接报错
        function (result) {
          if (result.status === Office.AsyncResultStatus.Failed) {
            console.error(result.error);
          }
          else {
            console.info(result.value.viewName, result.value.viewType)
          }
        }
      );
    }
  }

}

